/*
 * IConnector.cpp
 *
 *  Created on: Oct 10, 2012
 *      Author: nam20485
 */

#include "IConnector.h"
#include "ByteStreamMessage.h"
#include "ControlMessage.h"
#include "Logger.h"

const Message* IConnector::Receive()
{
	Logger::log("[IConnector::Receive() - enter]\n\r");

	const Packet* pPacket = DecodePacket();
	if (pPacket != 0)
	{
		switch (pPacket->getType())
		{
		case Message::NONE:
			// return 0
			break;
		case Message::STANDARD:
			return new Message(pPacket->getBytes());
		case Message::CONTROL:
			return new ControlMessage(pPacket->getBytes());
			break;
		case Message::BYTE_STREAM:
			return new ByteStreamMessage(pPacket->getBytes());
		}

		delete pPacket;
		pPacket = 0;
	}

	Logger::log("[IConnector::Receive() - packet NOT received]\n\r");
	Logger::log("[IConnector::Receive() - exit]\n\r");

	return 0;
}

const Packet* IConnector::DecodePacket()
{
	Logger::log("[IConnector::DecodePacket() - enter]\n\r");

	unsigned long length = 0;

	// type
	Message::Type eType = Message::NONE;
	length = sizeof(Message::Type);
	BYTE pTypeBuff[length];
	if (ReadBytes(pTypeBuff, length) == length)
	{
		memcpy( &eType, pTypeBuff, length);

		// size
		Packet::SIZE_T size = 0;
		length = sizeof(Packet::SIZE_T);
		BYTE pLengthBuff[length];
		if (ReadBytes(pLengthBuff, length) == length)
		{
			memcpy( &size, pLengthBuff, length);

			length = size;
			if (length > 0)
			{
				// bytes
				BYTE pByteBuff[length];
				if (ReadBytes(pLengthBuff, length) == length)
				{
					return new const Packet(eType, pByteBuff, size);
				}
			}
		}
	}

	Logger::log("[IConnector::DecodePacket() - failed decoding packet]\n\r");
	Logger::log("[IConnector::DecodePacket() - exit]\n\r");

	return 0;
}

bool IConnector::Send(const Message& message)
{
	unsigned int length = message.ToBytes();
	if (length > 0)
	{
		Message::BYTE pMessage[length];
		if (message.ToBytes(pMessage) == length)
		{
			Packet packet(message.TYPE, pMessage, length);
			length = packet.ToBytes();
			if (length > 0)
			{
				Packet::BYTE pPacket[length];
				if (packet.ToBytes(pPacket) == length)
				{
					if (WriteBytes(pPacket, length) == length)
					{
						return true;
					}
				}
			}
		}
	}
	return false;
}
